//
//  HomeViewController.m
//  groupProject
//
//  Created by mac on 15/12/17.
//  Copyright © 2015年 mac. All rights reserved.
//

#import "HomeViewController.h"
#import "Config.h"
#import "SearchViewController.h"
#import "MessageViewController.h"
#import "LocateTableViewController.h"
#import "FunRectView.h"
#import "HPScrollAndPageView.h"
#import "HomeTableViewCell.h"
#import "HomeTableCellButton.h"
#import "SVPullToRefresh.h"
#import "DataModel.h"
#import "NetConnect.h"
#import "UIImageView+WebCache.h"
@interface HomeViewController () <UINavigationControllerDelegate, UISearchBarDelegate, UIScrollViewDelegate, UITableViewDataSource, UITableViewDelegate>

@end

@implementation HomeViewController {
    UISearchBar *homesea;
    UIScrollView *homescroll;
    UIPageControl *homescrollPageCtr;
    UIView *cusHeadView;
    UITableView *hometable;
    HPScrollAndPageView *scrollAndPageView;
    UITableView * roatTableView;
    UIScrollView * tableScroll;
    NSArray *testarray;
    NSArray *tmpimage;
    NetConnect *netconnect;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //初始化全局变量
    cusHeadView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, HEADVIEW_HEIGHT)];
    cusHeadView.backgroundColor = [UIColor grayColor];
    hometable = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, CONTENT_HEIGHT) style:UITableViewStyleGrouped];
    hometable.dataSource = self;
    hometable.delegate = self;
    hometable.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    
    netconnect = [NetConnect new];
    [netconnect firstConnect];

    //testarray
     testarray = [NSArray arrayWithObjects:[NSArray arrayWithObjects:@"user_head",@"user_head",@"user_head", nil], [NSArray arrayWithObjects:@"user_head",@"user_head",@"user_head", nil], [NSArray arrayWithObjects:@"user_head",@"user_head",@"user_head", nil], [NSArray arrayWithObjects:@"user_head",@"user_head",@"user_head", nil], [NSArray arrayWithObjects:@"user_head",@"user_head",@"user_head", nil], [NSArray arrayWithObjects:@"user_head",@"user_head",@"user_head", nil], [NSArray arrayWithObjects:@"user_head",@"user_head",@"user_head", nil], [NSArray arrayWithObjects:@"user_head",@"user_head",@"user_head", nil],[NSArray arrayWithObjects:@"user_head",@"user_head",@"user_head", nil], [NSArray arrayWithObjects:@"user_head",@"user_head",@"user_head", nil], [NSArray arrayWithObjects:@"user_head",@"user_head",@"user_head", nil], [NSArray arrayWithObjects:@"user_head",@"user_head",@"user_head", nil],nil];
    
    [self setNavigationItem];
    self.navigationController.delegate = self;
    
    //添加主页分组的tableview
    //hometable.backgroundColor = [UIColor colorWithRed:250/255.0 green:180/255.0 blue:0/255.0 alpha:1];
    hometable.backgroundColor = [UIColor colorWithWhite:0.98 alpha:1];
    [self.view addSubview:hometable];
    [self drawHeadView];
    //[self drawTableScrollview];
    
   // tmpimage =[NSArray arrayWithObjects:@"1.jpg",@"2.jpg",@"3.jpg",@"4.jpg",@"5.jpg",@"6.jpg",@"7.jpg",@"8.jpg",@"9.jpg", nil];
    tmpimage =[NSArray arrayWithObjects:@"user_head",@"user_head",@"user_head",@"user_head",@"user_head",@"user_head",@"user_head",@"user_head",@"user_head", nil];
 
    
    
    //添加SVpulltorefresh
    __block HomeViewController *tmpSelf=self;
    [hometable addPullToRefreshWithActionHandler:^{
        [tmpSelf pullAction];
    }];
    
    
    // Do any additional setup after loading the view.

}


-(void)viewWillAppear:(BOOL)animated {
    NSMutableArray *tmparray = [NSMutableArray array];
    for (int i = 0; i < 5; i++) {
        //第二次请求获取图片
        UIImageView *tmpimageview = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCROLL_HEIGHT)];
        tmpimageview.image = [UIImage imageNamed:@"user_head.png"];
        [tmparray addObject:tmpimageview];
        NSLog(@"占位图片。。。。。");
    }
    scrollAndPageView.imageViewArray = tmparray;
}

-(void) viewDidAppear:(BOOL)animated {
    int64_t delayInSeconds = 2.0;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        scrollAndPageView.imageViewArray = netconnect.datamodel.SCImgeViewArray;
        //[hometable reloadData];
        NSLog(@"刷新网页完成");
        [hometable.pullToRefreshView stopAnimating];
    });
}

- (void) pullAction {
    NSLog(@"将要刷新网页");
    NSLog(@"正在刷新网页");

    int64_t delayInSeconds = 2.0;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
//        [self.tableView beginUpdates];
//        [self.dataSource insertObject:[NSDate date] atIndex:0];
//        [weakSelf.tableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationBottom];
//        [weakSelf.tableView endUpdates];
        scrollAndPageView.imageViewArray = netconnect.datamodel.SCImgeViewArray;
        //[hometable reloadData];
        NSLog(@"刷新网页完成");
        [hometable.pullToRefreshView stopAnimating];
    });

}

//draw tableview的头视图
- (void) drawHeadView {
    //scrollview 区
    scrollAndPageView = [[HPScrollAndPageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCROLL_HEIGHT)];
    //从服务器获取图片
    //scrollAndPageView.imageViewArray = netconnect.datamodel.SCImgeViewArray;
    [cusHeadView addSubview:scrollAndPageView];
    
    //btn 区
    NSArray *titleArray = [NSArray arrayWithObjects:@"新品抢购", @"精品推荐",@"年末大促",@"订单查询", @"新品抢购", @"以后再想",@"优惠劵",@"订单查询",nil];
    UIView *btnView = [[UIView alloc] initWithFrame:CGRectMake(0, SCROLL_HEIGHT, SCREEN_WIDTH, SCREEN_WIDTH*0.4)];
    btnView.backgroundColor = [UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:1.0];
    for (int i = 0; i< 8; i++) {
        FunRectView *funView = [[FunRectView alloc] initWithFrame:CGRectMake((i%4)*SCREEN_WIDTH/4.0, i/4 * SCREEN_WIDTH *0.2, SCREEN_WIDTH/4.0, SCREEN_WIDTH *0.2) andImage:@"user_head.png" andTitle:titleArray[i]];
        funView.btntag = i;
        [btnView addSubview:funView];
    }
    
    //添加一个躺着的tableview
    [self drawRoatTableView];
    [cusHeadView addSubview:roatTableView];
    [cusHeadView addSubview:btnView];
    hometable.tableHeaderView = cusHeadView;
    
    //[hometable.tableFooterView addSubview: netconnect.datamodel.SCImgeViewArray[0]];
}

- (UITableView *) drawRoatTableView {
    roatTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, SCREEN_WIDTH*0.75, SCREEN_WIDTH*0.4, SCREEN_WIDTH)];
    
    roatTableView.center = CGPointMake(SCREEN_WIDTH*0.5, SCREEN_WIDTH*0.2+SCREEN_WIDTH*0.75);
    roatTableView.transform = CGAffineTransformMakeRotation(-M_PI_2);
    roatTableView.showsVerticalScrollIndicator = NO;

    roatTableView.dataSource = self;
    roatTableView.delegate = self;
    
    return roatTableView;
}



//给tableview 添加一个scrollview
- (UIScrollView *) drawTableScrollview {
    tableScroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_WIDTH*0.4)];
    tableScroll.contentSize = CGSizeMake(SCREEN_WIDTH*0.28*7, 0);
    tableScroll.showsHorizontalScrollIndicator = NO;
    tableScroll.bounces = NO;
    
    NSArray *tmp =[NSArray arrayWithObjects:@"1.jpg",@"2.jpg",@"3.jpg",@"4.jpg",@"5.jpg",@"6.jpg",@"7.jpg",@"8.jpg",@"9.jpg", nil];
    
    for (int i = 0 ; i < 7 ; i++) {
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(i*SCREEN_WIDTH*0.28, 0, SCREEN_WIDTH*0.28, SCREEN_WIDTH*0.28)];
        imageView.image = [UIImage imageNamed:tmp[i]];
    
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(i*SCREEN_WIDTH*0.28, SCREEN_WIDTH*0.28, SCREEN_WIDTH*0.28, SCREEN_WIDTH*0.12)];
        label.text = @"商品名\n商品价格";
        [tableScroll addSubview:imageView];
        [tableScroll addSubview:label];
    }
    
    
    return tableScroll;
}


#pragma mark - 导航栏代理

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
//    if (viewController  == self) {
        self.navigationController.navigationBar.tintColor = [UIColor yellowColor];
        self.navigationController.navigationBar.alpha =1.0;
        self.navigationController.navigationBar.translucent = NO;
//    } else {
//        self.navigationController.navigationBar.tintColor = [UIColor yellowColor];
//        self.navigationController.navigationBar.alpha =1.0;
//        self.navigationController.navigationBar.translucent = YES;
//    }

    NSLog(@"#pragma mark - 导航栏代理");
}

- (void) setNavigationItem{
    //设置导航栏的右button 右btn为message按钮
    UIImage *mes = [UIImage imageNamed:@"newmessage"];
    mes = [mes imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:mes style:UIBarButtonItemStyleDone target:self action:@selector(messageBtnClick)];
    
    //设置 导航栏的 商店log
    UIImageView *logView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH *0.09, NAVIGATION_BAR_HEIGHT-10)];
    UIImage *shopLog = [UIImage imageNamed:@"shopName"];
    shopLog = [shopLog imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    logView.image = shopLog;
    UIBarButtonItem * shoplogtbn = [[UIBarButtonItem alloc] initWithCustomView:logView];
    
    //地址定位 按钮
    UIBarButtonItem *addrbtn = [[UIBarButtonItem alloc] initWithTitle:@"上海" style:UIBarButtonItemStylePlain target:self action:@selector(locateCurClick)];
    [addrbtn setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:12]} forState:UIControlStateNormal];
    addrbtn.tintColor = [UIColor redColor];
    
    //设置navigationItem leftBarButtonItems
    NSArray *leftBtnArray = [NSArray arrayWithObjects:shoplogtbn, addrbtn, nil];
    self.navigationItem.leftBarButtonItems = leftBtnArray;
    
    //设置导航栏上的 searchbar
    homesea = [[UISearchBar alloc] init];
    // homesea = [[UISearchBar alloc] initWithFrame:CGRectMake(SCREEN_WIDTH/2.0 - SCREEN_WIDTH*0.1 , STATUS_BAR_HEIGHT , SCREEN_WIDTH * 0.2, NAVIGATION_BAR_HEIGHT)];
    homesea.delegate = self;  //设置searchbar的代理
    homesea.placeholder = @"";
    self.navigationItem.titleView = homesea;
    //homesea.barTintColor = [UIColor yellowColor];
    
    UIView *tmp = [homesea.subviews objectAtIndex:0];  //不支持7.0之前的版本
    UITextField *textfield = [tmp.subviews objectAtIndex:1];
    textfield.backgroundColor = [UIColor clearColor];
    textfield.layer.borderWidth = 1;
    textfield.layer.cornerRadius = 5;
    textfield.layer.borderColor = [UIColor lightGrayColor].CGColor;
    textfield.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"搜索您想找的商品" attributes:@{NSForegroundColorAttributeName:[UIColor lightGrayColor], NSFontAttributeName:[UIFont systemFontOfSize:12]}];
    [[tmp.subviews objectAtIndex:0] removeFromSuperview];  //釜底抽薪  免得从其他vc切换回来  会出现短暂阴影；
    //textfield.textAlignment = NSTextAlignmentLeft;
}

#pragma  mark - button click methods

- (void) messageBtnClick {
    NSLog(@"messageBtnClick");
    MessageViewController *messageVC = [[MessageViewController alloc] init];
    messageVC.view.backgroundColor = [UIColor redColor];
    [self.navigationController pushViewController:messageVC animated:YES];
}

- (void) locateCurClick {
    
    NSLog(@"locateCurClick");
    LocateTableViewController *locateTV = [LocateTableViewController new];
    locateTV.view.backgroundColor = [UIColor orangeColor];
    [self.navigationController  pushViewController:locateTV animated:YES];
}





#pragma mark - delegate methods
//searchbar delegate 产生新的ViewController
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    //[searchBar resignFirstResponder];
    SearchViewController *searchVC = [[SearchViewController alloc] init];
    searchVC.view.backgroundColor = [UIColor yellowColor];
    [self.navigationController pushViewController:searchVC animated:NO];
    return NO; //使searchbar 取消第一相应
}



#pragma mark - 手势
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:NO];
    //[homesea resignFirstResponder];
}

//view 将显示的时候 修改 状态栏字体颜色
//- (void)viewWillAppear:(BOOL)animated {
//    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];
//}

/*//view 退出时 改回状态栏字体颜色
 - (void)viewWillDisappear:(BOOL)animated {
 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:YES];
 }
 */

#pragma mark - tableview datasource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (tableView == hometable) {
        return 1;
    }
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView == hometable) {
        return 8;
    }
    return tmpimage.count;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString * kReuseID = @"reuseID";
    static NSString * kReuseID0 = @"reuseID0";
    static NSString * KReuseID1 = @"reused2";
    if (tableView == hometable) {
        HomeTableViewCell *cell;
        if (indexPath.row == 0) {
            cell = [tableView cellForRowAtIndexPath:indexPath];
            if (cell == nil) {
                cell = [[HomeTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kReuseID0 andIndexPath:indexPath];
            }
        } else {
            cell = [tableView dequeueReusableCellWithIdentifier:kReuseID];
            if (cell == nil) {
                cell = [[HomeTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kReuseID andIndexPath:indexPath];
            }
        }
        NSArray *tmp = testarray[indexPath.row];
        [cell setData:tmp];
        return cell;
        
    } else {
        
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:KReuseID1];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:KReuseID1];
            cell.frame = CGRectMake(0, 0, SCREEN_WIDTH*0.4, SCREEN_WIDTH*.28);
            cell.contentView.transform = CGAffineTransformMakeRotation(M_PI_2);
        }
        cell.imageView.image = [UIImage imageNamed:tmpimage[indexPath.row]];
        return cell;
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
//    if (indexPath.section == 0) {
//        return SCREEN_WIDTH * 0.4;
//    }
    if (tableView == hometable) {
        return SCREEN_WIDTH * 0.3;
    } else  {
        return SCREEN_WIDTH * 0.4;
    }
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
